package grails4j
import twitter4j.Status
import twitter4j.Twitter
import twitter4j.TwitterException
import twitter4j.TwitterFactory
import twitter4j.http.AccessToken
import twitter4j.http.RequestToken
import twitter4j.User

class PrincipalController {

	static String consumerKey = "94l4la4Ews1sFTDwWxCTKQ"
	static String consumerSecret = "jfM506MvlpzYEqalaQmUjdsFOECk6E3OfaGDVTgAw"
	
    def index = {
		redirect(action: "entrada", params: params)
	}
	
	def entrada = {
		if(session.autenticado == null){
			redirect(action: "saida", params: params)
		}
		
		else{
			
		//Twitter twitter = session.twitter
		
		AccessToken accessToken = session.autenticado
		
		Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(consumerKey, consumerSecret, accessToken)
		User usuario = twitter.showUser(twitter.getScreenName());
		String bio = usuario.getDescription()
		String id = usuario.getId()
		
		List<Status> twits = twitter.getUserTimeline()
		
		params.nome = twitter.getScreenName()
		//params.status = men.getText()
		params.twits = twits
		params.bio = bio
		params.id = id
			
		}
	}
	
	def twit = {
		if(session.autenticado == null){
			redirect(action: "saida", params: params)
		}
		
		else{
			AccessToken accessToken = session.autenticado
		
			Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(consumerKey, consumerSecret, accessToken)
			
			String mensagem = params.mensagem
			
			twitter.updateStatus(mensagem)
			
			redirect(action: "entrada")
		}
	}
	
	def saida = {
		redirect(controller:'login',action:'index')
	}
	
	def logout = {
		if(session.autenticado == null){
			redirect(action: "saida")
		}
		else{
			AccessToken accessToken = session.autenticado
			Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(consumerKey, consumerSecret, accessToken)
			twitter.shutdown();
			session.autenticado = null
			redirect(controller:'login',action:'index')
		}
	}
	
}
